from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.

from django.views import View
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken
from .form import UserForm,LoginUserForm
from utils.redis_utils import RedisHelper

class Register(APIView):
    permission_classes = [AllowAny]

    def get(self,request):
        return render(request,'register.html')

    def post(self,request):
        form = UserForm(request.POST)
        if form.is_valid():
            user = form.save()
            # username = form.cleaned_data['username']  # 从 cleaned_data 获取字段值
            # password = form.cleaned_data['password2']
            # CustomUser.objects.create_user(username=username,password=password)
            return JsonResponse({'code': 200, 'message': '注册成功'})
        else:
            return JsonResponse({'code': 400, 'message': '注册失败', 'errors': form.errors})


class Login(APIView):
    permission_classes = [AllowAny]
    redis = RedisHelper()
    def get(self,request):
        return render(request,'login.html')

    def post(self,request):
        form = LoginUserForm(request.POST)
        if form.is_valid():
            user = form.cleaned_data.get('user')
            token = RefreshToken.for_user(user)
            access_token = str(token.access_token)
            self.redis.set_cache(access_token, {
                "id": user.id,
                "mobile": user.mobile
            }, timeout=360)
            return Response({
                "user": {
                    "id": user.id,
                    "username": user.username,
                    "email": user.email
                },
                'code':200,
                'message': '登录成功',
                "token": str(access_token)
            }, status=status.HTTP_200_OK)
        else:
            # 如果表单验证失败，返回错误信息
            return Response({'code': 400, 'message': '登录失败', 'errors': form.errors})